package com.batch.adance.migrate;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.batch.adance.jdbc.Person;
import com.batch.adance.jdbc.PersonRowMapper;

@Repository
public class PersonBatchDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	private static final String SAVE_SQL = "insert into person_buf_bark01 ( `name`, `per_desc`, `sex`, `score`, `price`) values(?,?,?,?,?)";
	private static final int BATCH_SIZE = 10000000;

	public List<Person> list() {
		return jdbcTemplate.query("select id,name,per_desc,create_time,update_time,sex,score,price from person_buf",
				new PersonRowMapper());
	}

	/**
	 * 
	 * 245760条数据做迁移
	 * 
	 批次10000时候。程序运行时间：19027ms
	 
	 批次100000时候。程序运行时间：10265ms
	 
	  批次1000000时候。程序运行时间：8775ms
	  
	   批次10000000时候。程序运行时间：9497ms
	 */
	public void save(final List<Person> list) {
		List<Object[]> args = transformPersonToObjects(list);
		int fromIndex = 0;
		int toIndex = BATCH_SIZE;
		while (fromIndex != args.size()) {
			if (toIndex > args.size()) {
				toIndex = args.size();
			}
			this.jdbcTemplate.batchUpdate(SAVE_SQL, args.subList(fromIndex, toIndex));
			fromIndex = toIndex;
			toIndex += BATCH_SIZE;
			if (toIndex > args.size())
				toIndex = args.size();
		}

	}

	private List<Object[]> transformPersonToObjects(List<Person> personList) {
		List<Object[]> list = new ArrayList<>();
		Object[] object = null;
		for (Person item : personList) {
			object = new Object[] { item.getName(), item.getPerDesc(), item.getSex(), item.getScore(),
					item.getPrice() };
			list.add(object);
		}
		return list;
	}
}
